package controllers

import (
	"net/http"

	"WHY_GIN/service"

	"github.com/gin-gonic/gin"
)

// SmartStopLossController 智能止损控制器
type SmartStopLossController struct{}

// NewSmartStopLossController 创建新的智能止损控制器
func NewSmartStopLossController() *SmartStopLossController {
	return &SmartStopLossController{}
}

// SetThresholdRequest 设置阈值请求结构
type SetThresholdRequest struct {
	Threshold    float64 `json:"threshold" binding:"required"` // 亏损阈值（如0.05表示5%）
	SupportLevel *float64 `json:"support_level,omitempty"`     // 可选的支撑位价格
	Symbol       string   `json:"symbol,omitempty"`            // 交易对（设置支撑位时需要）
}

// SetSupportLevelRequest 设置支撑位请求结构
type SetSupportLevelRequest struct {
	Symbol string  `json:"symbol" binding:"required"` // 交易对
	Price  float64 `json:"price" binding:"required"`  // 支撑位价格
}

// SetLossThreshold 设置亏损阈值
// @Summary 设置智能止损亏损阈值
// @Description 设置智能止损的亏损阈值，当卖单亏损达到此比例时自动以限价卖出，可选设置支撑位监控
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Param request body SetThresholdRequest true "亏损阈值信息"
// @Success 200 {object} map[string]interface{} "设置成功"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/threshold [post]
func (sslc *SmartStopLossController) SetLossThreshold(c *gin.Context) {
	var req SetThresholdRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "参数错误",
			"message": err.Error(),
		})
		return
	}

	// 验证阈值范围
	if req.Threshold <= 0 || req.Threshold >= 1 {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "参数错误",
			"message": "亏损阈值必须在0到1之间",
		})
		return
	}

	// 如果设置了支撑位，验证参数
	if req.SupportLevel != nil {
		if req.Symbol == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"error":   "参数错误",
				"message": "设置支撑位时必须指定交易对",
			})
			return
		}
		if *req.SupportLevel <= 0 {
			c.JSON(http.StatusBadRequest, gin.H{
				"error":   "参数错误",
				"message": "支撑位价格必须大于0",
			})
			return
		}
	}

	// 设置亏损阈值
	err := service.SetSmartStopLossThreshold(req.Threshold)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "设置失败",
			"message": err.Error(),
		})
		return
	}

	// 如果设置了支撑位，同时设置支撑位
	responseData := gin.H{
		"threshold":     req.Threshold,
		"threshold_pct": req.Threshold * 100,
		"description":   "当卖单亏损达到此比例时将自动以限价卖出（滑点不超过1%）",
	}

	if req.SupportLevel != nil {
		err = service.SetSupportLevelForSymbol(req.Symbol, *req.SupportLevel)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "支撑位设置失败",
				"message": err.Error(),
			})
			return
		}
		responseData["support_level"] = gin.H{
			"symbol": req.Symbol,
			"price":  *req.SupportLevel,
			"note":   "当价格跌破支撑位时将停止买单",
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "智能止损设置成功",
		"data":    responseData,
	})
}

// GetStatus 获取智能止损状态
// @Summary 获取智能止损状态
// @Description 获取智能止损管理器的当前状态信息
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "获取成功"
// @Router /api/smart-stop-loss/status [get]
func (sslc *SmartStopLossController) GetStatus(c *gin.Context) {
	status := service.GetSmartStopLossStatus()

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "获取智能止损状态成功",
		"data":    status,
	})
}

// QuickSetThreshold 快速设置5%亏损阈值
// @Summary 快速设置5%亏损阈值
// @Description 快速设置智能止损阈值为5%（符合需求场景）
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "设置成功"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/quick-set-5pct [post]
func (sslc *SmartStopLossController) QuickSetThreshold(c *gin.Context) {
	// 设置5%亏损阈值
	threshold := 0.05
	err := service.SetSmartStopLossThreshold(threshold)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "设置失败",
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "快速设置成功（5%亏损阈值）",
		"data": gin.H{
			"threshold":     threshold,
			"threshold_pct": threshold * 100,
			"description":   "当任何卖单亏损达到5%时将自动以市价卖出",
			"feature":       "自动监控所有卖单，无需手动添加",
		},
	})
}

// StopMonitoring 停止智能止损监控
// @Summary 停止智能止损监控
// @Description 停止智能止损监控服务
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "停止成功"
// @Router /api/smart-stop-loss/stop [post]
func (sslc *SmartStopLossController) StopMonitoring(c *gin.Context) {
	service.StopSmartStopLossManager()

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "智能止损监控已停止",
		"data": gin.H{
			"status": "stopped",
			"note":   "所有卖单监控已停止，不再自动执行止损",
		},
	})
}

// StartMonitoring 启动智能止损监控
// @Summary 启动智能止损监控
// @Description 启动智能止损监控服务
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "启动成功"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/start [post]
func (sslc *SmartStopLossController) StartMonitoring(c *gin.Context) {
	// 重新初始化智能止损管理器
	service.InitSmartStopLossManager()

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "智能止损监控已启动",
		"data": gin.H{
			"status":         "running",
			"description":    "正在自动监控所有卖单的亏损情况",
			"check_interval": "每5秒检查一次",
		},
	})
}

// GetThreshold 获取当前亏损阈值
// @Summary 获取当前亏损阈值
// @Description 获取当前设置的亏损阈值
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "获取成功"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/threshold [get]
func (sslc *SmartStopLossController) GetThreshold(c *gin.Context) {
	status := service.GetSmartStopLossStatus()

	// 检查是否有错误
	if errorMsg, exists := status["error"]; exists {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "获取失败",
			"message": errorMsg,
		})
		return
	}

	threshold, _ := status["loss_threshold"].(float64)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "获取亏损阈值成功",
		"data": gin.H{
			"threshold":     threshold,
			"threshold_pct": threshold * 100,
			"description":   "当卖单亏损达到此比例时将自动以限价卖出（滑点不超过1%）",
		},
	})
}

// SetSupportLevel 设置支撑位
// @Summary 设置支撑位价格
// @Description 为指定交易对设置支撑位价格，当价格跌破支撑位时将停止买单
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Param request body SetSupportLevelRequest true "支撑位信息"
// @Success 200 {object} map[string]interface{} "设置成功"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/support-level [post]
func (sslc *SmartStopLossController) SetSupportLevel(c *gin.Context) {
	var req SetSupportLevelRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "参数错误",
			"message": err.Error(),
		})
		return
	}

	// 验证价格
	if req.Price <= 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "参数错误",
			"message": "支撑位价格必须大于0",
		})
		return
	}

	// 设置支撑位
	err := service.SetSupportLevelForSymbol(req.Symbol, req.Price)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "设置失败",
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "支撑位设置成功",
		"data": gin.H{
			"symbol":      req.Symbol,
			"price":       req.Price,
			"description": "当价格跌破此支撑位时将停止买单",
		},
	})
}

// GetSupportLevels 获取所有支撑位状态
// @Summary 获取所有支撑位状态
// @Description 获取当前设置的所有支撑位价格和状态
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "获取成功"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/support-levels [get]
func (sslc *SmartStopLossController) GetSupportLevels(c *gin.Context) {
	status := service.GetAllSupportLevelsStatus()

	// 检查是否有错误
	if errorMsg, exists := status["error"]; exists {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "获取失败",
			"message": errorMsg,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "获取支撑位状态成功",
		"data":    status,
	})
}

// GetSupportLevel 获取指定交易对的支撑位
// @Summary 获取指定交易对的支撑位
// @Description 获取指定交易对的支撑位价格
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Param symbol path string true "交易对"
// @Success 200 {object} map[string]interface{} "获取成功"
// @Failure 404 {object} map[string]interface{} "支撑位不存在"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/support-level/{symbol} [get]
func (sslc *SmartStopLossController) GetSupportLevel(c *gin.Context) {
	symbol := c.Param("symbol")
	if symbol == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "参数错误",
			"message": "交易对不能为空",
		})
		return
	}

	price, exists, err := service.GetSupportLevelForSymbol(symbol)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "获取失败",
			"message": err.Error(),
		})
		return
	}

	if !exists {
		c.JSON(http.StatusNotFound, gin.H{
			"error":   "支撑位不存在",
			"message": "该交易对未设置支撑位",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "获取支撑位成功",
		"data": gin.H{
			"symbol": symbol,
			"price":  price,
		},
	})
}

// RemoveSupportLevel 移除支撑位
// @Summary 移除指定交易对的支撑位
// @Description 移除指定交易对的支撑位设置
// @Tags 智能止损管理
// @Accept json
// @Produce json
// @Param symbol path string true "交易对"
// @Success 200 {object} map[string]interface{} "移除成功"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /api/smart-stop-loss/support-level/{symbol} [delete]
func (sslc *SmartStopLossController) RemoveSupportLevel(c *gin.Context) {
	symbol := c.Param("symbol")
	if symbol == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "参数错误",
			"message": "交易对不能为空",
		})
		return
	}

	err := service.RemoveSupportLevelForSymbol(symbol)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "移除失败",
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "支撑位移除成功",
		"data": gin.H{
			"symbol": symbol,
		},
	})
}
